const fs = require('fs')
const path = require('path')
const archiver = require('archiver')

function statSync(filePath) {
  return fs.statSync(filePath)
}

function readFileSync(filePath) {
  return fs.readFileSync(filePath)
}

function fullPath(parent, child) {
  return path.isAbsolute(child) ? child : path.join(parent, child)
}

function basename(filePath) {
  return path.basename(filePath)
}

function createZip(sourceDir) {
  const zipName = `${basename(sourceDir)}.zip`
  const outPath = `${sourceDir}/${zipName}`
  return new Promise((resolve, reject) => {
    const output = fs.createWriteStream(outPath)
    const archive = archiver('zip')

    // 监听输出文件流的事件
    output.on('close', () => resolve(outPath))

    // 监听归档过程中的错误
    archive.on('error', reject)

    // 将输出流管道到归档流
    archive.pipe(output)

    // 添加目录到归档
    archive.glob('**/*', {
      cwd: sourceDir,
      ignore: [zipName]
    })

    // 完成归档
    archive.finalize()
  })
}

module.exports = {
  statSync,
  readFileSync,
  fullPath,
  basename,
  createZip
}